package com.yx.common.utils;

import com.sun.mail.util.MailSSLSocketFactory;

import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.util.Properties;

public class MailUtil {
    private String email;//收件人邮箱
    private String code;

    public MailUtil(String email, String code) {
        this.email = email;
        this.code = code;
    }

    public void run(){
//        1、创建连接对象
//        2、创建邮件对象
//        3、发送一封激活邮件
        String from = "2786698724@qq.com";//发件人电子邮箱
        String host = "smtp.qq.com";//指定发送邮件的主机smtp.qq.com(QQ)|smtp.163.com(网易)

        Properties properties = System.getProperties();//获取系统属性
        properties.setProperty("mail.smtp.host",host);//设置邮件服务器
        properties.setProperty("mail.smtp.auth","true");//打开认证
        try {
//            QQ邮箱需要下面这段代码，163邮箱不需要
            MailSSLSocketFactory sf = new MailSSLSocketFactory();
            sf.setTrustAllHosts(true);
            properties.put("mail.smtp.ssl.enable","true");
            properties.put("mail.smtp.ssl.socketFactory",sf);

//            1、获取默认session对象
            Session session = Session.getDefaultInstance(properties, new Authenticator() {
                @Override
                protected PasswordAuthentication getPasswordAuthentication() {
//                    return super.getPasswordAuthentication();
                    return new PasswordAuthentication("2786698724@qq.com","oxzrtqnpiqrlddgd");
                }
            });
//            2、创建邮件对象
            MimeMessage message = new MimeMessage(session);
//            2.1设置发件人
            message.setFrom(new InternetAddress(from));
//            2.2设置接收人
            message.addRecipient(Message.RecipientType.TO,new InternetAddress(email));
//            2.3设置邮件主题
            message.setSubject("邮箱验证");
//            2.4设置邮件内容
            String content = "<html><head></head><body><h1>欢迎来到3M网站</h1><h1>这是一份验证码文件</h1><h3>验证码，code="+code+"</href></h3></body></html>";
            message.setContent(content,"text/html;charset=UTF-8");
//            3、发送邮件
            Transport.send(message);
            System.out.println("code"+code);
            System.out.println("邮件发送成功！");

        }catch(Exception e){
            e.printStackTrace();
        }
    }
}
